package com.david.utils;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;

import java.io.File;

public class jacobUtil {
    public static boolean word2PDF(String inputFile, String pdfFile) {

        File tofile = new File(pdfFile);
        if (tofile.exists()) {
            return true;
        }

        long beginTime = System.nanoTime();

        // 打开word应用程序
        ActiveXComponent app = new ActiveXComponent("Word.Application");
        try {
            // ActiveXComponent app = new ActiveXComponent("000209FF-0000-0000-C000-000000000046");
            // 设置word不可见
            app.setProperty("Visible", false);
            // 获得word中所有打开的文档,返回Documents对象
            Dispatch docs = app.getProperty("Documents").toDispatch();
            // 调用Documents对象中Open方法打开文档，并返回打开的文档对象Document
            Dispatch doc = Dispatch.call(docs, "Open", inputFile, false, true).toDispatch();
            Object wdFormatPDF;
            // 调用Document对象的SaveAs方法，将文档保存为pdf格式
            /*
             * Dispatch.call(doc,"SaveAs",pdfFile,wdFormatPDF //word保存为pdf格式宏，值为17 );
             */
            Dispatch.call(doc, "ExportAsFixedFormat",pdfFile,17);

            // 关闭文档
            Dispatch.call(doc, "Close", false);

            long endTime = System.nanoTime();
            long l = endTime - beginTime;
            System.out.println("--word文件转换pdf文件--------------------------差时：" + l + "耗时: " + l / 1000000000 + " 秒");

            return true;
        } catch (Exception e) {
            System.out.println(e);
            return false;
        }finally{
            // 关闭word应用程序
            if(app!=null) app.invoke("Quit", 0);
        }
    }

}
